package com.dlwx.parttimetalent.base;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.baidu.BaiduListener;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.service.MyService;
import com.dlwx.parttimetalent.ui.LoginActivity;
import com.dlwx.parttimetalent.utils.DialogUtils;
import com.dlwx.parttimetalent.utils.GpsUtil;
import com.dlwx.parttimetalent.utils.HxUtils;
import com.dlwx.parttimetalent.utils.NotificationsUtils;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.views.MyProgressLoading;
import com.dlwx.parttimetalent.views.RedPackectDialog;
import com.dlwx.parttimetalent.wxapi.QQUtiles;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.gyf.barlibrary.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;

/**
 * @作者 wch
 * @create at 2017/1/12 0012 下午 4:24
 * @name 父类activity
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    public Context ctx;
    public Bundle savedInstanceState;
    private Display display;
    private int height;
    public String[] per = {Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};

    private SharedPreferences sp;
    public MyProgressLoading loadingDialog;
    private BaiduListener mListener;
    private DialogBroadCast receiver;
    private RxPermissions rxpermissions;
    private NormalDialog locationDialog;
    private NormalDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        ctx = this;
//        sp = getSharedPreferences(SPUtils.SP_MODE, MODE_PRIVATE);
//        loading = new MyProgressLoading(ctx, R.style.DialogStyle);
//        uploadShopsLoading = new MyUploadShopsLoading(ctx, R.style.DialogStyle);
//        //为了防止底部菜单上移
        display = getWindowManager().getDefaultDisplay();
        height = display.getHeight();
//        initView();
//        initDate();
//        initListener();
        if(loadingDialog==null){
            loadingDialog=new MyProgressLoading(this,R.style.DialogStyle);
        }
        IntentFilter intentFilter=new IntentFilter(Constant.RECEIVER_ACCOUNT);
        receiver=new DialogBroadCast();
        registerReceiver(receiver,intentFilter);
        setImmer(R.color.ooo);
        rxpermissions=new RxPermissions(this);
        if(!GpsUtil.isOPen(this)){
            locationDialog = DialogUtils.getLocationDialog(this, "定位服务未开启", "不能看到附近用户，部分功能无法使用");
            locationDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    locationDialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    locationDialog.dismiss();
                    //跳转GPS设置界面
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0);
//                   GpsUtil.openGPS(BaseActivity.this);
                }
            });
        };
        if(!rxpermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)){
             locationDialog = DialogUtils.getLocationDialog(this, "定位服务未开启", "不能看到附近用户，部分功能无法使用");
            locationDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    locationDialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    rxpermissions.request( Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if(aBoolean){
                                        locationDialog.dismiss();
                                    }
                                }
                            });
                }
            });
        };
        checkNoti();
    }

    /**
     * 检查通知权限是否开启
     */
   private void checkNoti(){
       boolean b=NotificationsUtils.isNotificationEnabled(this);
       if(!b){
           locationDialog = DialogUtils.getNotiDialog(this, "通知服务未开启", "下单收不到通知，部分功能无法使用");
           locationDialog.setOnBtnClickL(new OnBtnClickL() {
               @Override
               public void onBtnClick() {
                   locationDialog.dismiss();
               }
           }, new OnBtnClickL() {
               @Override
               public void onBtnClick() {
//                   Intent intent = new Intent(Settings.ACTION_SETTINGS);
//                   startActivity(intent);
                   Intent localIntent = new Intent();
                   localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   if (Build.VERSION.SDK_INT >= 9) {
                       localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                       localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                   } else if (Build.VERSION.SDK_INT <= 8) {
                       localIntent.setAction(Intent.ACTION_VIEW);
                       localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
                       localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                   }
                   startActivity(localIntent);
               }
           });
       }
   }
    @Override
    public void onClick(View v) {

    }

    /**
     * 谈吐司
     *
     * @param message
     */
    public void toast(Object message) {
        Toast toast = Toast.makeText(ctx, message + "", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, height / 13);
        toast.show();

    }

    /**
     * 调试弹吐司
     */
//    public void debugToast(Object message) {
//        Snackbar.make(null,"",Snackbar.LENGTH_SHORT).show();
////    }

    /**
     * log信息
     *
     * @param message
     */
    public void logmess(Object message) {
        Log.i("Tag", message + "");
    }
    /**
     * wchlog信息
     *
     * @param message
     */
//    public void wch(Object message) {
//        LogUtiles.logI(message);
//    }


    private Toolbar toolbar;

    /**
     * 初始化头布局
     *
     * @param toolbar
     */
    public void initToolBar(Toolbar toolbar) {
        this.toolbar = toolbar;
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        if (!isWhite) {
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_launcher);
//        } else {
//            getSupportActionBar().setHomeAsUpIndicator(R.mipmap.icon_heisejiantou);
//
//        }

    }

    private void showpopu() {
//        TSnackbar snackbar = TSnackbar
//                .make(toolbar, "网络不好请检查您的网络连接", TSnackbar.LENGTH_SHORT);
//        View snackbarView = snackbar.getView();
//        snackbarView.setBackgroundColor(Color.parseColor("#00FF4111"));
//        snackbar.setDuration(1000);
//
//        snackbar.show();
    }

    /**
     * 网络类型
     */
    private int netMobile;

    /**
     * 初始化时判断有没有网络
     */
    public boolean inspectNet() {
//        this.netMobile = NetUtil.getNetWorkState(BaseActivity.this);
        return isNetConnect();
        // if (netMobile == 1) {
        // System.out.println("inspectNet：连接wifi");
        // } else if (netMobile == 0) {
        // System.out.println("inspectNet:连接移动数据");
        // } else if (netMobile == -1) {
        // System.out.println("inspectNet:当前没有网络");
        //
        // }
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    // 写一个广播的内部类，当收到动作时，结束activity
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            unregisterReceiver(this); // 这句话必须要写要不会报错，不写虽然能关闭，会报一堆错
            ((Activity) context).finish();
        }
    };

    public void register() {
        // 在当前的activity中注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("base_finish_activity");
        registerReceiver(this.broadcastReceiver, filter); // 注册
    }

    public void close() {
        Intent intent = new Intent();
        intent.setAction("base_finish_activity"); // 说明动作
        sendBroadcast(intent);// 该函数用于发送广播
        finish();
    }

    //定义请求
    private static final int READ_CONTACTS_REQUEST = 1;
    public boolean isget = false;

    //当用户执行的操作需要权限时候进行询问
    public void getPermissionToReadUserContacts() {
        /**
         * 1)使用ContextCompat.chefkSelfPermission(),因为Context.permission
         * 只在棒棒糖系统中使用
         * 2）总是检查权限（即使权限被授予）因为用户可能会在设置中移除你的权限*/
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //权限为获取，检查用户是否被询问过并且拒绝了，如果是这样的话，给予更多
            //解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
                //在界面上展示为什么需要读取联系人
                Toast.makeText(this, "需要读取联系人和调用摄像头才能正常工作", Toast.LENGTH_SHORT).show();
            }
            //发起请求获得用户许可,可以在此请求多个权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION},
                    READ_CONTACTS_REQUEST);
        } else {
            isget = true;
        }

    }
    //从requestPermissions()方法回调结果


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == READ_CONTACTS_REQUEST) {
            if (grantResults.length == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "读取联系人权限获得", Toast.LENGTH_SHORT).show();


            } else if (grantResults.length == 3 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                isget = false;
                Toast.makeText(this, "读取联系人失败", Toast.LENGTH_SHORT).show();
            } else if (grantResults.length == 3 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                isget = true;
                Toast.makeText(this, "获取摄像头权限成功", Toast.LENGTH_SHORT).show();
            } else {
                isget = true;
                Toast.makeText(this, "获得摄像头权限失败", Toast.LENGTH_SHORT).show();
            }

        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onStop() {
        super.onStop();
//        locationService.unregisterListener(mListener); //注销掉监听
//        locationService.stop(); //停止定位服务
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(loadingDialog!=null){
            loadingDialog.dismiss();
        }
        if(dialog!=null){
            dialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
        unregisterReceiver(receiver);


    }

    public void setImmer(int color) {
        ImmersionBar.with(this)
                .transparentStatusBar()  //透明状态栏，不写默认透明色
                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
//                .statusBarColor(R.color.colorPrimary)     //状态栏颜色，不写默认透明色
                .navigationBarColor(R.color.ooo) //导航栏颜色，不写默认黑色
                .barColor(R.color.ooo)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                .statusBarAlpha(1.0f)  //状态栏透明度，不写默认0.0f
                .navigationBarAlpha(1.0f)  //导航栏透明度，不写默认0.0F
                .barAlpha(1.0f)  //状态栏和导航栏透明度，不写默认0.0f
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
//                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
//                .setViewSupportTransformColor(toolbar) //设置支持view变色，支持一个view，不指定颜色，默认和状态栏同色，还有两个重载方法
//                .addViewSupportTransformColor(toolbar)  //设置支持view变色，可以添加多个view，不指定颜色，默认和状态栏同色，还有两个重载方法
//                .statusBarView(view)  //解决状态栏和布局重叠问题
//                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                .statusBarColorTransform(color)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportView()  //移除通过setViewSupportTransformColor()方法指定的view
//                .removeSupportView(toolbar)  //移除指定view支持
//                .removeSupportAllView() //移除全部view支持
                .init();  //必须调用方可沉浸式
    }

//    /**
//     * 获取位置
//     */
//    public void getLocation() {
//        client = new AMapLocationClient(ctx);
//        option = new AMapLocationClientOption();
//        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//
//        option.setGpsFirst(true);
//        //超时时间
//        option.setHttpTimeOut(5000);
//        option.setNeedAddress(true);
//        //刷新时间为两个小时
//        option.setInterval(3600000);
//        client.setLocationOption(option);
//        client.setLocationListener(listener);
//        client.startLocation();
//    }
//
//    AMapLocationListener listener = new AMapLocationListener() {
//        @Override
//        public void onLocationChanged(AMapLocation aMapLocation) {
//            if (aMapLocation == null) {
//                toast("定位失败");
//                return;
//            }
//
//
//            lat = aMapLocation.getLatitude();
//            lng = aMapLocation.getLongitude();
//            city = aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getAddress();
//            Log.d("hahah", lat + "\n" + lng);
//            sp.edit().putString(SPUtils.lng, String.valueOf(lng)).commit();
//            sp.edit().putString(SPUtils.lat, String.valueOf(lat)).commit();
//
//
//        }
//    };

    private class DialogBroadCast  extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null){
                return;
            }
            if(TextUtils.equals(intent.getAction(),Constant.RECEIVER_ACCOUNT)){
                int type=intent.getIntExtra("type",0);
                switch (type){
                    case Constant.MSG_ACCOUNT_REPEAT:
                        dialog = DialogUtils.getNormalDialogOneBtn(BaseActivity.this, "", "账号在其他设备登录", "确定");
                        dialog.setOnBtnClickL(new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                                SPUtils.clear(BaseActivity.this);
                                SPUtils.put(BaseActivity.this, Constant.isLogin, false);
                                SPUtils.put(BaseActivity.this, Constant.First_START, false);
                                JPushInterface.cleanTags(BaseActivity.this, 0);
//                                               JPushInterface.deleteTags();
                                QQUtiles qqUtils = new QQUtiles();
                                qqUtils.logout(BaseActivity.this);
                                HxUtils.loginOut();
                                Intent stopIntent = new Intent(BaseActivity.this, MyService.class);
                                stopService(stopIntent);
                                Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(i);
                            }
                        });
                        break;
                    case Constant.MSG_RED_PACEKT:
                        String id=intent.getStringExtra("id");
                        RedPackectDialog dialog1=new RedPackectDialog(BaseActivity.this,id);
                        dialog1.show();
                        break;
                }
            }
        }
    }
//    long exitTime = 0;
//    // 点击返回按钮
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if(dialog.isShowing()){
//                return false;
//            }else{
//                return super.onKeyDown(keyCode, event);
//            }
////            if ((System.currentTimeMillis() - exitTime) > 2000) {
////                ToastUtils.toastForShort(BaseActivity.this, "再按一次退出程序");
////                exitTime = System.currentTimeMillis();
////                return false;
////            } else {
////                finish();
////            }
//        }else{
//
//            return super.onKeyDown(keyCode, event);
//        }
//    }
}